package com.zdsoft.site.mina.client;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.api.IoFutureListener;
import org.apache.mina.api.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.ConnectFuture;
import org.apache.mina.transport.nio.NioTcpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zdsoft.site.mina.model.Institution;
import com.zdsoft.site.mina.model.MessgeHeader;
import com.zdsoft.site.mina.model.PackageHeader;
import com.zdsoft.site.mina.model.customEnum.InstitutionType;
import com.zdsoft.site.mina.model.customEnum.InstructionCode;
import com.zdsoft.site.mina.model.customEnum.SystemType;
import com.zdsoft.site.mina.model.customEnum.YesNoIndicator;

public class I4670 {
	
	private static Logger logger=LoggerFactory.getLogger(I4670.class);
	private static String str="X05700356P88880004670001200000000000000000000000000000000<?xml version=\"1.0\" encoding=\"GB2312\"?><MsgText><MsgHdr><Ver>v1.0</Ver><SysType>4</SysType><InstrCd>46700</InstrCd><TradSrc>0</TradSrc><SvInst><InstType>0</InstType><InstId>P8888000</InstId></SvInst><Date>20151209</Date><Time>140701</Time><RqRef><Ref>1449641221362</Ref></RqRef><LstFrag>Y</LstFrag></MsgHdr><Ccy>0</Ccy><BusType>4</BusType><Dgst/></MsgText>";
	public static void main(String[] args) {
		
		NioTcpClient connector=new NioTcpClient();
		connector.getFilterChain().addLast("logger", new LoggingFilter());
		connector.getFilterChain().addLast("codec", 
                new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
		
		connector.setHandler(new I4670Handler());
		
		ConnectFuture cf = connector.connect(new InetSocketAddress("120.55.174.14", 8015));
		cf.awaitUninterruptibly();
		logger.debug("连接完成");
		cf.addListener(new IoFutureListener<ConnectFuture>() {
			@Override
			public void operationComplete(ConnectFuture future) {
				if(future.isConnected()){
					IoSession session=future.getSession();
					
					
					PackageHeader h=new PackageHeader();
					h.setFlag("012");
					h.setInstId("P8888000");
					h.setInstrCd(InstructionCode.A46700.getValue());
					h.setBodyLength(0);
					//1.头部
					MessgeHeader header=new MessgeHeader();
					header.setVersion("v1.0");
					header.setCreateDate("20151215");
					header.setCreateTime("104030");
					header.setServiceInstitution(new Institution());
					header.setBankInstitution(new Institution());
					header.setLastFragment(YesNoIndicator.N);
					header.setInstructionCode(InstructionCode.A46700);
					header.setTradeSource(InstitutionType.A0);
					header.setSystemType(SystemType.A4);
					logger.debug("获取连接对应的session={}",session.getId());
					logger.debug("发送数据.");
					session.write(str);
				}
			}
		});
	}

}
